package com.scala.learn.jdbcDemo

import java.sql.{Connection, DriverManager}

import org.apache.spark.rdd.JdbcRDD
import org.apache.spark.{SparkConf, SparkContext}

/**
  * @Copyright: Shanghai Definesys Company.All rights reserved.
  * @Description:   1 缺点是条件之能是 long类型的始末位置
  *              、 2、如何扩展
  *
  * @author: chuhaitao
  * @since: 2019/3/8 20:12
  * @history:
  *          1.2019/3/8 created by chuhaitao
  */
object JDBCDemo {

 // val driver = "oracle.jdbc.driver.OracleDriver"
  val driver = "com.mysql.jdbc.Driver"
 // val url="jdbc:oracle:thin:@fmwdbdev.cscec8b.com.cn:1521:fmwdbdev"
  val url="jdbc:mysql://localhost:3306/test?characterEncoding=UTF8"
 // val username = "FIS"
  val username = "root"
 // val password = "FIS"
  val password = "123456"

  def getConn(): Connection = {
    Class.forName(driver).newInstance()
    DriverManager.getConnection(url, username, password)

  }


  def main(args: Array[String]): Unit = {

    val conf = new SparkConf().setAppName("jdbcDemo").setMaster("local[*]")

    val sc = new SparkContext(conf)


    val jdbcRdd = new JdbcRDD(
      sc,
      getConn,
      "SELECT u.id ,username FROM USER u  where id>=? and id<=?",
      0,
      100,
      2,
      rs => {
       var userId = rs.getInt("id")
      var userName = rs.getString("username")
       (userId, userName)

      }
    )

    val r = jdbcRdd.collect().toBuffer
    print(r)
  }
}
